const KEY = 'as_ach_earned_ids'

export function getCachedEarnedIds() {
  try {
    const raw = localStorage.getItem(KEY)
    if (!raw) return new Set()
    const arr = JSON.parse(raw)
    if (!Array.isArray(arr)) return new Set()
    return new Set(arr.map(String))
  } catch { return new Set() }
}

export function updateCacheFromList(list) {
  try {
    const arr = Array.from(list).map(String)
    localStorage.setItem(KEY, JSON.stringify(arr))
  } catch {}
}

export function computeNewlyEarned(currentEarnedIds) {
  const cached = getCachedEarnedIds()
  const newly = []
  for (const id of currentEarnedIds) {
    if (!cached.has(String(id))) newly.push(String(id))
  }
  return newly
}

export function replaceCacheWith(currentEarnedIds) {
  updateCacheFromList(new Set(Array.from(currentEarnedIds).map(String)))
}
